package com.visionork.android.tai.activity;

import java.util.List;

import com.visionork.android.tai.TaiApp;
import com.visionork.android.tai.model.Episode;
import com.visionork.android.tai.model.Program;
import com.visionork.android.tai.model.ProgramRepositoryBase;
import com.visionork.android.tai.model.ProgramType;
import com.visionork.android.tai.model.Video;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EpisodeActivityBase extends ListActivity {
	public static final String KEY_PROGRAMTYPE = "KEY_PROGRAMTYPE";
	public static final String KEY_PROGRAM_URL = "KEY_PROGRAM_URL";
	public static final String KEY_EPISODE_URL = "KEY_EPISODE_URL";
	public static final String KEY_DYNAMIC = "KEY_DYNAMIC";
	protected int programType;
	protected String programUrlLink;
	protected String episodeUrlLink;
	protected boolean dynamic;
	protected VideoItemAdapter itemAdapter;

	protected class VideoItemAdapter extends ArrayAdapter<Video> {

		public VideoItemAdapter(Context context, int textViewResourceId,
				List<Video> objects) {
			super(context, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.episode_list_item, null);
			}

			Video epi = getItem(position);

			TextView tvTitle = (TextView) v.findViewById(R.id.title);
			tvTitle.setText(epi.getTitle());

			return v;
		}
	}

	private class LoadVideoTask extends AsyncTask<Void, Void, Void> {
		private boolean useCache;
		protected ProgressDialog pd;

		public LoadVideoTask(boolean useCache) {
			this.useCache = useCache;
		}

		@Override
		protected Void doInBackground(Void... params) {
			if (!dynamic) {
				getRepository().getProgramByUrlLink(programUrlLink)
						.getEpisodeByUrlLink(episodeUrlLink).getVideos();
				if (!useCache
						|| getRepository().getProgramByUrlLink(programUrlLink)
								.getEpisodeByUrlLink(episodeUrlLink)
								.getVideosRef().size() == 0) {
					getRepository().getProgramByUrlLink(programUrlLink)
							.getEpisodeByUrlLink(episodeUrlLink)
							.getVideos(false);
				}
			} else {
				TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink).getVideos();
				if (!useCache
						|| TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink)
								.getVideosRef().size() == 0) {
					TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink).getVideos(
							false);
				}
			}

			return null;
		}

		private ProgramRepositoryBase getRepository() {
			switch (programType) {
			case ProgramType.Show:
				return TaiApp.getShowRepository();
			case ProgramType.Drama:
				return TaiApp.getDramaRepository();
			}

			return null;
		}

		@Override
		protected void onPreExecute() {
			Resources res = getResources();
			pd = ProgressDialog.show(EpisodeActivityBase.this, null,
					res.getString(R.string.load), true, false);
		}

		@Override
		protected void onPostExecute(Void param) {
			itemAdapter.notifyDataSetChanged();
			pd.dismiss();
		}
	}

	private class LoadYoutubeTask extends AsyncTask<String, Void, Void> {
		protected ProgressDialog pd;
		protected String youtubeID;
		protected String urlString;

		@Override
		protected Void doInBackground(String... params) {
			try {
				urlString = params[0];
				Episode epi;
				if (!dynamic) {
					Program prog = getRepository().getProgramByUrlLink(
							programUrlLink);
					epi = prog.getEpisodeByUrlLink(episodeUrlLink);
				} else {
					epi = TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink);
				}

				Video video = epi.getVideoByUrlLink(urlString);
				youtubeID = video.getVideoID();
			} catch (Throwable e) {

			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			Resources res = getResources();
			pd = ProgressDialog.show(EpisodeActivityBase.this, null,
					res.getString(R.string.load), true, false);
		}

		@Override
		protected void onPostExecute(Void param) {
			pd.dismiss();
			Resources res = getResources();								
			if (youtubeID != null && youtubeID.trim().length() > 0) {
				Intent intent = new Intent(Intent.ACTION_VIEW,
						Uri.parse("vnd.youtube:" + youtubeID));
				startActivity(intent);
			} else {
				Toast.makeText(getApplicationContext(), res.getString(R.string.none_youtube_video),
				          Toast.LENGTH_SHORT).show();
			}
			
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.video_list);
		Intent intent = getIntent();

		programUrlLink = intent.getStringExtra(KEY_PROGRAM_URL);
		episodeUrlLink = intent.getStringExtra(KEY_EPISODE_URL);
		programType = intent.getIntExtra(KEY_PROGRAMTYPE, ProgramType.Show);
		dynamic = intent.getBooleanExtra(KEY_DYNAMIC, false);

		Episode epi;
		if (!dynamic) {
			epi = getRepository().getProgramByUrlLink(programUrlLink)
					.getEpisodeByUrlLink(episodeUrlLink);
			itemAdapter = new VideoItemAdapter(EpisodeActivityBase.this,
					R.layout.video_list_item, epi.getVideosRef());

		} else {
			epi = TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink);
			itemAdapter = new VideoItemAdapter(EpisodeActivityBase.this,
					R.layout.video_list_item, epi.getVideosRef());
		}

		TextView tvTitle = (TextView) (findViewById(R.id.title));
		tvTitle.setText(epi.getTitle());

		setListAdapter(itemAdapter);

		loadData(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.videolist_option_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			loadData(false);
			return true;
		case R.id.share:
			Episode epi;
			if (!dynamic) {
				epi = getRepository().getProgramByUrlLink(programUrlLink)
						.getEpisodeByUrlLink(episodeUrlLink);

			} else {

				epi = TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink);

			}
			String subject = "FWD: " + epi.getTitle();
			String text = epi.getTitle() + " - " + epi.getUrlLink();
			TaiApp.share(this, subject, text);
			return true;
		}

		return super.onMenuItemSelected(featureId, item);

	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Episode epi;
		if (!dynamic) {
			Program prog = getRepository().getProgramByUrlLink(programUrlLink);
			epi = prog.getEpisodeByUrlLink(episodeUrlLink);
		} else {
			epi = TaiApp.getLatestEpisodeByUrlLink(episodeUrlLink);
		}

		Video video = epi.getVideos().get(position);
		String urlLink = video.getUrlLink();

		LoadYoutubeTask task = new LoadYoutubeTask();
		task.execute(new String[] { urlLink });
	}

	private ProgramRepositoryBase getRepository() {
		switch (programType) {
		case ProgramType.Show:
			return TaiApp.getShowRepository();
		case ProgramType.Drama:
			return TaiApp.getDramaRepository();
		}

		return null;
	}

	private void loadData(boolean useCache) {
		LoadVideoTask task = new LoadVideoTask(useCache);
		task.execute(new Void[] {});
	}
}
